﻿Imports System.Data.Linq
Imports HTLibrary
Imports TNCBAL
Imports TNCDAL
Public Class ucManageUsers
    Dim roleCtrl As New CRoleController
    Private _iRole As Integer = -1
    Private _doiMatKhau As Boolean = False
    Private _currentUser As tblUser = Nothing
    Dim uCtrl As New CUserController
#Region "ListView"
    Private Sub lvRoles_SelectedIndexChanged1(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvRoles.SelectedIndexChanged
        If (lvRoles.SelectedItems.Count > 0) Then
            HienThiGridUser()
        End If
    End Sub
#End Region

#Region "Gridview"
    Private Sub dgUsers_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgUsers.SelectionChanged
        Try
            'hiển thị thông tin người dùng
            Dim _idCurrentUser As Integer = dgUsers.CurrentRow.Cells("ID_User").Value
            _currentUser = uCtrl.SelectRecordByID(_idCurrentUser)
            BindDataToTextBox()
        Catch ex As Exception
        End Try
    End Sub
#End Region

#Region "Buttons"

    Private Sub btXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        If (_currentUser IsNot Nothing) Then
            If (MessageBox.Show("Có phải bạn muốn xoá:" + _currentUser.UserName + " ?", "Xác nhận", MessageBoxButtons.YesNo) = vbYes) Then
                _currentUser.IsActive = False
                uCtrl.UpdateRecordWithoutAttach(_currentUser)
                'hien thi lai datagridview
                HienThiGridUser()
                HienThiNut_Thuong()
            End If
        End If
        ''lay ra ID cua user hien tai
        'Dim _uID As Integer = dgUsers.CurrentRow.Cells("ID_User").Value
        'Dim _uUserName As String = dgUsers.CurrentRow.Cells("UserName").Value
        'If (MessageBox.Show("Có phải bạn muốn xoá:" + _uUserName + " ?", "Xác nhận", MessageBoxButtons.YesNo) = vbYes) Then
        '    uCtrl.DeleteRecord(_uID)
        '    'hien thi lai datagridview
        '    HienThiGridUser()
        '    HienThiNut_Thuong()
        'End If
    End Sub

    Private Sub btThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        'gọi form User
        Dim idRole As Integer = -1
        If (lvRoles.SelectedItems.Count > 0) Then
            idRole = CInt(lvRoles.SelectedItems(0).SubItems(0).Text)
        End If
        XoaTrangTextBox()
        HienThiNut_Sua()
        'Init obj
        _currentUser = New tblUser
        txtUserName.Focus()
    End Sub
    Private Sub btSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        'lay ra ID cua user hien tai
        HienThiNut_Sua()
        txtFullName.Enabled = True
        txtFullName.Focus()
    End Sub

    Private Sub btDoiMatKhau_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btDoiMatKhau.Click
        txtPassword.Enabled = True
        txtPassword2.Enabled = True
        _doiMatKhau = True
        HienThiNut_Sua()
        txtPassword.Focus()
    End Sub
    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Try
            Dim _id_User As Integer = dgUsers.CurrentRow.Cells("ID_User").Value
            _currentUser = uCtrl.SelectRecordByID(_id_User)
        Catch ex As Exception
        End Try
        BindDataToTextBox()
        HienThiNut_Thuong()
    End Sub
    Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        ThemNguoiDung()
    End Sub
#End Region

#Region "Utilities Function, Sub"
    Private Sub MyTextBox_Enter(ByVal sender As Object, ByVal e As EventArgs) Handles txtFullName.Enter, txtUserName.Enter, txtPassword.Enter, txtPassword2.Enter
        ' Kick off SelectAll asyncronously so that it occurs after Click
        Dim txt As TextBox = CType(sender, TextBox)
        BeginInvoke(DirectCast(Sub() txt.SelectAll(), Action))
    End Sub

    Private Sub HienThiListView()
        'xoa het may cai cu
        lvRoles.Items.Clear()
        'lay danh sach cac role
        Dim roles = roleCtrl.SelectAllRecord()
        For Each tbl In roles
            Dim item As New ListViewItem(tbl.ID_Role)
            item.SubItems.Add(tbl.RoleName)
            'item.Text = tbl.RoleName
            lvRoles.Items.Add(item)
        Next
        If (lvRoles.Items.Count > 0) Then
            lvRoles.Items(0).Selected = True
        End If
    End Sub

    Public Sub HienThiGridUser()
        XoaTrangTextBox()
        HienThiNut_Thuong()
        EnableControls(False)
        'lay danh sach nguoi su dung theo nhom quyen
        Dim uCtrl As New CUserController
        Dim item As ListViewItem = lvRoles.SelectedItems(0)
        _iRole = CInt(item.SubItems(0).Text) 'lay ma nhom nguoi dung
        Dim LocalDataTable = uCtrl.SelectAllRecord()
        dgUsers.DataSource = (From tbl In LocalDataTable _
                              Where tbl.ID_Role = _iRole
                               Select tbl.ID_User, _
                                      tbl.UserName, _
                                      tbl.FullName)
        dgUsers.Columns("ID_User").Visible = False
        dgUsers.Columns("Username").Width = 100
        'thông tin role
        Dim role As tblRole = roleCtrl.SelectRecordByID(_iRole)
        panelUsers.TitleText = "Users of " & role.RoleName
    End Sub

    Private Sub AnThongBaoLoi()
        lblFullNameError.Visible = False
        lblPassword2Error.Visible = False
        lblPasswordError.Visible = False
        lblUserNameError.Visible = False
    End Sub

    Private Sub HienThiNut_Thuong()
        'dgCountries.AllowUserToAddRows = False
        'dgCountries.AllowUserToDeleteRows = False
        'dgCountries.ReadOnly = True
        btnAdd.Enabled = True
        btnDel.Enabled = True
        btnEdit.Enabled = True
        btDoiMatKhau.Enabled = True

        btnUpdate.Enabled = False
        btnCancel.Enabled = False
        dgUsers.Enabled = True
    End Sub

    Private Sub HienThiNut_Sua()
        btnAdd.Enabled = False
        btnDel.Enabled = False
        btnEdit.Enabled = False
        btDoiMatKhau.Enabled = False

        btnUpdate.Enabled = True
        btnCancel.Enabled = True
        dgUsers.Enabled = False
    End Sub

    Private Sub XoaTrangTextBox()
        AnThongBaoLoi()
        _currentUser = Nothing
        _doiMatKhau = False
        txtFullName.Text = ""
        txtPassword.Text = ""
        txtPassword2.Text = ""
        txtUserName.Text = ""
        txtUserName.Enabled = True
        txtFullName.Enabled = True
        txtPassword.Enabled = True
        txtPassword2.Enabled = True
    End Sub

    Public Function ThemNguoiDung() As Boolean
        AnThongBaoLoi()
        If (txtUserName.Text = "") Then
            lblUserNameError.Visible = True
            txtUserName.Focus()
            Return False
        End If
        'check user name co ton tai hay chua
        If (_currentUser.ID_User < 1) Then
            If (uCtrl.CheckUserExists(txtUserName.Text)) Then
                MessageBox.Show("Tên đăng nhập này đã tồn tại! Chọn tên đăng nhập khác!")
                txtUserName.Text = ""
                txtUserName.Focus()
                Return False
            End If
        End If
        'kiem tra xem cac thong tin da nhap du chua        
        If (txtFullName.Text = "") Then
            lblFullNameError.Visible = True
            txtFullName.Focus()
            Return False
        End If
        'check Pass 1 va Pass 2
        If (_currentUser.ID_User < 1 Or _doiMatKhau = True) Then
            If (txtPassword.Text = "") Then
                lblPasswordError.Visible = True
                txtPassword.Focus()
                Return False
            End If
            If (txtPassword2.Text = "") Then
                lblPassword2Error.Visible = True
                txtPassword2.Focus()
                Return False
            End If
            If (txtPassword.Text <> txtPassword2.Text) Then
                txtPassword.Text = ""
                txtPassword2.Text = ""
                lblPassword2Error.Visible = True
                lblPasswordError.Visible = True
                txtPassword.Focus()
                Return False
            End If
        End If

        With _currentUser
            .UserName = txtUserName.Text
            .FullName = txtFullName.Text
            If (_currentUser.ID_User < 1 Or _doiMatKhau = True) Then
                .Password = CThanh_Utilities.getMd5Hash(txtPassword.Text)
            Else
                .Password = _currentUser.Password
            End If
            .ID_Role = _iRole
        End With
        Dim idCurr As Integer = _currentUser.ID_User
        If (_currentUser.ID_User > 0) Then
            uCtrl.UpdateRecordWithoutAttach(_currentUser)
            'ghi log
            Dim objLogController As New LogController
            objLogController.Insert(enumAction.Edit, "User: " & _currentUser.UserName)
        Else
            uCtrl.InsertRecord(_currentUser)
            idCurr = _currentUser.ID_User
            'ghi log
            Dim objLogController As New LogController
            objLogController.Insert(enumAction.Add, "User: " & _currentUser.UserName)
        End If
        HienThiGridUser()
        Dim indexRow As Integer = -1
        'lấy ra vị trí của port vừa thêm hoặc chỉnh sửa vào
        indexRow = FindIndexOfPortInGrid(idCurr)
        'Set current row
        dgUsers.CurrentCell = dgUsers.Rows(indexRow).Cells(1)
        dgUsers.Rows(indexRow).Selected = True
        'tro ve trạng thái thường
        HienThiNut_Thuong()
        HienThiNut_Thuong()
        Return True
    End Function
    Private Function FindIndexOfPortInGrid(ByVal id As Integer) As Integer
        Dim index As Integer = 0
        For Each row As DataGridViewRow In dgUsers.Rows
            If (row.Cells("ID_User").Value = id) Then
                index = row.Index
                Exit For
            End If
        Next
        Return index
    End Function

    Private Sub EnableControls(ByVal val As Boolean)
        txtFullName.Enabled = val
        txtUserName.Enabled = val
        txtPassword.Enabled = val
        txtPassword2.Enabled = val
    End Sub

    Private Sub BindDataToTextBox()
        AnThongBaoLoi()
        If (_currentUser IsNot Nothing) Then
            'hien thi ra cac textbox
            txtFullName.Text = _currentUser.FullName
            txtUserName.Text = _currentUser.UserName
            txtPassword.Text = "Password"
            txtPassword2.Text = "Password"
            txtPassword.Enabled = False
            txtPassword2.Enabled = False
            btDoiMatKhau.Enabled = True
        Else
            XoaTrangTextBox()
        End If

    End Sub
#End Region

    Private Sub ucManageUsers_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        HienThiListView()
        HienThiNut_Thuong()
        EnableControls(False)
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        DataGridViewHelper.DataGridView_InitEvent(dgUsers)
    End Sub
End Class
